import { useEffect, useState } from "react";
import "./Map.css";
import AMapLoader from "@amap/amap-jsapi-loader";

export default function Map(props) {
  let map = null;
  const [mapLoaded, setMapLoaded] = useState(false); // 地图是否加载完成
  const [positionValue, setPositionValue] = useState('');
  const [startAddress, setstartAddress] = useState('');
  const [endAddress, setendAddress] = useState('');
  useEffect(() => {
    if (startAddress) {
      props.change(startAddress)
    }
  }, [])
  useEffect(() => {
    window._AMapSecurityConfig = {
      securityJsCode: "161c1f92a11bde40c72db8322707fce7",
    };
    AMapLoader.load({
      key: "e53fdba0df28048e219cb2e8636db4ca", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ["AMap.Scale", "AMap.Geocoder", "AMap.Driving"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
    })
      .then((AMap) => {
        map = new AMap.Map("container", {
          zoom: 3, // 初始化地图级别
          resizeEnable: true,
        });
        setMapLoaded(true);
        // 浏览器定位
        AMap.plugin('AMap.Geolocation', function () {
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：5s
            position: 'RB',    //定位按钮的停靠位置
            offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
            zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

          });
          map.addControl(geolocation);
          geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          });
        });

        // 逆地理编码
        var geocoder = new AMap.Geocoder({
          city: "010", //城市设为北京，默认：“全国”
          radius: 1000 //范围，默认：500
        });
        var marker = new AMap.Marker();;
        //解析定位结果
        function onComplete(data) {
          var lnglat = data.position;
          map.add(marker);
          marker.setPosition(lnglat);

          geocoder.getAddress(lnglat, function (status, result) {
            if (status === 'complete' && result.regeocode) {
              var address = result.regeocode.formattedAddress;
              document.getElementById('address').value = address;
              console.log(address, '定位结果');
              setstartAddress(address)
              localStorage.setItem('startAddress', address)
              var str = [];
              str.push('定位结果：' + address);
              document.getElementById('result').innerHTML = str.join('<br>');
            } else {
              console.log('根据经纬度查询地址失败')
            }
          });
        }
        //解析定位错误信息
        function onError(data) {
          document.getElementById('status').innerHTML = '定位失败'
          document.getElementById('result').innerHTML = '失败原因排查信息:' + data.message + '</br>浏览器返回信息：' + data.originMessage;
        }
        function regeoCode() {

          var lnglat = document.getElementById('lnglat').value.split(',');
          map.add(marker);
          marker.setPosition(lnglat);

          geocoder.getAddress(lnglat, function (status, result) {
            if (status === 'complete' && result.regeocode) {
              var address = result.regeocode.formattedAddress;
              document.getElementById('address').value = address;
              console.log('终点位置', address);

              setendAddress(address)
              localStorage.setItem('endAddress', address)
            } else {
              console.log('根据经纬度查询地址失败')
            }
          });
        }

        map.on('click', function (e) {
          document.getElementById('lnglat').value = e.lnglat;
          regeoCode();
        })
        document.getElementById("regeo").onclick = regeoCode;
        document.getElementById('lnglat').onkeydown = function (e) {
          if (e.keyCode === 13) {
            regeoCode();
            return false;
          }
          return true;
        };
        if (!mapLoaded) {
          console.log('地图加载失败');
          return
        }
        // 驾车导航
        //构造路线导航类
        var driving = new AMap.Driving({
          map: map,
          panel: "panel"
        });
        // 根据起终点名称规划驾车导航路线
        driving.search([
          { keyword: startAddress.trim() ? startAddress.trim() : '河北省保定市竞秀区保定国家高新区天鹅西路213号保定市乐凯中学(北校区)' },
          { keyword: endAddress.trim() ? endAddress.trim() : '河北省保定市竞秀区保定国家高新区保定院子(向阳店)吉翔园' }
        ], function (status, result) {
          if (status === 'complete') {
            console.log('绘制驾车路线完成')
          } else {
            console.log('获取驾车数据失败：' + result)
          }
        });
      })
      .catch((e) => {
        console.log(e);
      });

    return () => {
      map?.destroy();
    };
  }, [startAddress, endAddress]);

  return (<>
    <div
      id="container"
      className="container"
      style={{ height: "400px" }}
    ></div>
    <div className="info">
      <p id="result"></p><hr />
    </div>
    <div className="input-card" style={{ width: '16rem', height: '0px', overflow: 'hidden' }}>
      <div className="input-item">
        <div className="input-item-prepend"><span className="input-item-text">经纬度</span></div>
        <input id='lnglat' type="text" value={positionValue} onChange={(e) => setPositionValue(e.target.value)} />
      </div>
      <div className="input-item">
        <div className="input-item-prepend"><span className="input-item-text" >地址</span></div>
        <input id='address' type="text" disabled />
      </div>
      <input id="regeo" type="button" className="btn" value="经纬度 -> 地址" />
    </div>
    <div id="panel"></div>
  </>);
}